<template>
  <div class="wechat-work-login">
    <div class="login-container">
      <div class="login-card">
        <div class="logo-section">
          <img src="/fylog1d.png" alt="Logo" class="logo" />
          <h1 class="app-title">柳州市妇幼保健院</h1>
          <p class="subtitle">企业微信登录</p>
        </div>
        
        <div class="login-content">
          <!-- 加载状态 -->
          <div v-if="loading" class="loading-section">
            <div class="loading-spinner"></div>
            <p class="loading-text">{{ loadingText }}</p>
          </div>
          
          <!-- 错误状态 -->
          <div v-else-if="error" class="error-section">
            <div class="error-icon">⚠️</div>
            <p class="error-message">{{ errorMessage }}</p>
            <button @click="retry" class="retry-btn">重试</button>
            <button @click="goToNormalLogin" class="normal-login-btn">使用账号密码登录</button>
          </div>
          
          <!-- 正常登录状态 -->
          <div v-else class="login-section">
            <div class="wechat-icon">
              <svg width="64" height="64" viewBox="0 0 24 24" fill="#07C160">
                <path d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 0 1 .213.665l-.39 1.48c-.019.07-.048.141-.048.213 0 .163.13.295.29.295a.326.326 0 0 0 .167-.054l1.903-1.114a.864.864 0 0 1 .717-.098 10.16 10.16 0 0 0 2.837.403c.276 0 .543-.027.811-.05-.857-2.578.157-4.972 1.932-6.446 1.703-1.415 4.882-1.786 7.608-.925.847-3.206-2.233-5.921-8.351-5.921zm-2.262 5.924a.716.716 0 1 1 0-1.433.716.716 0 0 1 0 1.433zm4.524 0a.716.716 0 1 1 0-1.433.716.716 0 0 1 0 1.433z"/>
                <path d="M15.309 11.468c-3.506 0-6.266 2.749-6.266 6.109 0 1.672.8 3.109 2.05 4.075a.402.402 0 0 1 .146.46l-.271 1.026c-.013.049-.034.098-.034.147 0 .113.092.204.201.204a.226.226 0 0 0 .116-.037l1.32-.772a.6.6 0 0 1 .497-.068c.758.232 1.55.342 2.241.342 3.506 0 6.266-2.749 6.266-6.109s-2.76-6.377-6.266-6.377zm-1.758 4.108a.496.496 0 1 1 0-.992.496.496 0 0 1 0 .992zm3.517 0a.496.496 0 1 1 0-.992.496.496 0 0 1 0 .992z"/>
              </svg>
            </div>
            <h2 class="login-title">企业微信登录</h2>
            <p class="login-description">请点击下方按钮开始企业微信登录</p>
            
            <button @click="startWeChatLogin" class="wechat-login-btn" :disabled="loading">
              <span class="btn-icon">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="white">
                  <path d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 0 1 .213.665l-.39 1.48c-.019.07-.048.141-.048.213 0 .163.13.295.29.295a.326.326 0 0 0 .167-.054l1.903-1.114a.864.864 0 0 1 .717-.098 10.16 10.16 0 0 0 2.837.403c.276 0 .543-.027.811-.05-.857-2.578.157-4.972 1.932-6.446 1.703-1.415 4.882-1.786 7.608-.925.847-3.206-2.233-5.921-8.351-5.921zm-2.262 5.924a.716.716 0 1 1 0-1.433.716.716 0 0 1 0 1.433zm4.524 0a.716.716 0 1 1 0-1.433.716.716 0 0 1 0 1.433z"/>
                  <path d="M15.309 11.468c-3.506 0-6.266 2.749-6.266 6.109 0 1.672.8 3.109 2.05 4.075a.402.402 0 0 1 .146.46l-.271 1.026c-.013.049-.034.098-.034.147 0 .113.092.204.201.204a.226.226 0 0 0 .116-.037l1.32-.772a.6.6 0 0 1 .497-.068c.758.232 1.55.342 2.241.342 3.506 0 6.266-2.749 6.266-6.109s-2.76-6.377-6.266-6.377zm-1.758 4.108a.496.496 0 1 1 0-.992.496.496 0 0 1 0 .992zm3.517 0a.496.496 0 1 1 0-.992.496.496 0 0 1 0 .992z"/>
                </svg>
              </span>
              企业微信登录
            </button>
            
            <div class="divider">
              <span>或</span>
            </div>
            
            <button @click="goToNormalLogin" class="normal-login-btn">
              使用账号密码登录
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { isWeChatWork } from '@/utils/wechat'
import api from '@/utils/api'
import { initVConsole } from '@/utils/vconsole'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

const loading = ref(false)
const error = ref(false)
const loadingText = ref('正在初始化...')
const errorMessage = ref('')
const isWeChatWorkEnv = ref(false)

// 页面初始化
onMounted(async () => {
  // 根据用户权限初始化vConsole调试工具
  initVConsole()
  
  // 检测企业微信环境
  isWeChatWorkEnv.value = isWeChatWork()
  
  // 检查URL参数，处理回调
  const code = route.query.code
  const state = route.query.state
  const token = route.query.token
  const errorParam = route.query.error
  const message = route.query.message
  
  if (errorParam) {
    // 处理错误回调
    handleError(decodeURIComponent(message || '登录失败'))
  } else if (token) {
    // 处理成功回调
    await handleSuccessCallback(token, route.query.userId, route.query.name)
  } else if (code) {
    // 处理授权码回调
    await handleCodeCallback(code, state)
  }
  // 移除自动登录逻辑，改为手动点击触发
})

// 开始企业微信登录
const startWeChatLogin = async () => {
  try {
    loading.value = true
    loadingText.value = '正在获取授权链接...'
    error.value = false
    
    // 获取授权URL
    const state = generateState()
    const response = await api.post('/api/wechatwork/auth-url', {
      // 不传递redirectUri，让后端使用默认的回调地址
      redirectUri: null,
      state: state
    })
    
    if (response.data.success) {
      loadingText.value = '正在跳转到企业微信...'
      // 跳转到企业微信授权页面
      window.location.href = response.data.data.authUrl
    } else {
      handleError(response.data.message || '获取授权链接失败')
    }
  } catch (err) {
    console.error('企业微信登录失败:', err)
    handleError('网络错误，请检查网络连接')
  }
}

// 处理授权码回调
const handleCodeCallback = async (code, state) => {
  try {
    loading.value = true
    loadingText.value = '正在验证授权信息...'
    
    // 调用登录API
    const response = await api.post('/api/wechatwork/login', {
      code: code,
      state: state
    })
    
    if (response.data.success && response.data.data.success) {
      const loginData = response.data.data
      await handleLoginSuccess(loginData)
    } else {
      const message = response.data.data?.message || response.data.message || '登录失败'
      handleError(message)
    }
  } catch (err) {
    console.error('处理授权码失败:', err)
    handleError('登录验证失败，请重试')
  }
}

// 处理成功回调
const handleSuccessCallback = async (token, userId, name) => {
  try {
    loading.value = true
    loadingText.value = '正在完成登录...'
    
    // 保存token到store
    await authStore.setWeChatWorkToken(token, {
      userId: userId,
      name: decodeURIComponent(name || '')
    })
    
    // 跳转到主页
    router.push('/')
  } catch (err) {
    console.error('处理成功回调失败:', err)
    handleError('登录完成失败，请重试')
  }
}

// 处理登录成功
const handleLoginSuccess = async (loginData) => {
  try {
    // 保存token和用户信息到store
    await authStore.setWeChatWorkToken(loginData.token, loginData.userInfo)
    
    // 跳转到主页
    router.push('/')
  } catch (err) {
    console.error('保存登录信息失败:', err)
    handleError('保存登录信息失败，请重试')
  }
}

// 处理错误
const handleError = (message) => {
  loading.value = false
  error.value = true
  errorMessage.value = message
}

// 重试
const retry = () => {
  error.value = false
  startWeChatLogin()
}

// 跳转到普通登录
const goToNormalLogin = () => {
  router.push('/login-mobile')
}

// 生成状态参数
const generateState = () => {
  return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
}
</script>

<style scoped>
.wechat-work-login {
  min-height: 100vh;
  background: linear-gradient(135deg, #07C160 0%, #00A854 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 400px;
}

.login-card {
  background: white;
  border-radius: 16px;
  padding: 40px 30px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.logo-section {
  margin-bottom: 40px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 16px;
}

.app-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.login-content {
  min-height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 加载状态 */
.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #07C160;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 16px;
  color: #666;
  margin: 0;
}

/* 错误状态 */
.error-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.error-icon {
  font-size: 48px;
}

.error-message {
  font-size: 16px;
  color: #e74c3c;
  margin: 0;
  text-align: center;
}

.retry-btn {
  padding: 12px 24px;
  background: #07C160;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.retry-btn:hover {
  background: #00A854;
}

/* 正常登录状态 */
.login-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.wechat-icon {
  margin-bottom: 10px;
}

.login-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.login-description {
  font-size: 14px;
  color: #666;
  margin: 0;
  text-align: center;
}

.wechat-login-btn {
  width: 100%;
  height: 50px;
  background: #07C160;
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.wechat-login-btn:hover:not(:disabled) {
  background: #00A854;
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(7, 193, 96, 0.4);
}

.wechat-login-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-icon {
  display: flex;
  align-items: center;
}

.divider {
  width: 100%;
  position: relative;
  text-align: center;
  margin: 20px 0;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #e1e5e9;
}

.divider span {
  background: white;
  padding: 0 16px;
  color: #666;
  font-size: 14px;
}

.normal-login-btn {
  width: 100%;
  height: 50px;
  background: transparent;
  color: #666;
  border: 2px solid #e1e5e9;
  border-radius: 12px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.normal-login-btn:hover {
  border-color: #07C160;
  color: #07C160;
}

/* 移动端适配 */
@media (max-width: 480px) {
  .wechat-work-login {
    padding: 10px;
  }
  
  .login-card {
    padding: 30px 20px;
  }
  
  .app-title {
    font-size: 20px;
  }
  
  .wechat-login-btn,
  .normal-login-btn {
    height: 45px;
    font-size: 15px;
  }
}
</style>